package com.zzx.magic.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzx.magic.entity.Menu;
import com.zzx.magic.entity.Role;
import com.zzx.magic.mapper.MenuMapper;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author Zhangxx
 * @Date 2024/6/14 14:52
 */
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Resource
    MenuMapper menuMapper;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        List<Menu> menus = menuMapper.selectList(new QueryWrapper<>());
        for(Menu menu: menus) {
            if(antPathMatcher.match(menu.getPattern(), requestUrl)) {
                List<Role> roles = new ArrayList<>();
                String[] roleArr = new String[roles.size()];
                for(int i= 0; i < roleArr.length; i++) {
                    roleArr[i] = roles.get(i).toString();
                }
                return SecurityConfig.createList(roleArr);
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}